package simulation;

import gui.MainGUI;
import gui.TabContainer;
import houseHold.House;

import java.awt.Color;

import javax.swing.JFrame;

import timer.Time;
import constants.Constants;
import controlComponents.GUIBuilder;
import db.DBConnection;

public class SimThread implements Runnable {

	public static boolean visual = false;

	public void run() {
		if (Time.dates.size() > 0) {
			for (int i = 0; i < Time.dates.size(); i++) {
				executeOnce(Time.dates.get(i));
			}
			MainGUI.SimSpeed.setEnabled(true);
		} else {
			executeOnce("2011-07-04");
			MainGUI.SimSpeed.setEnabled(true);
		}
	}

	public void executeOnce(String date) {

		House.getInstance().activateFridge();
		MainGUI.getInstance().setSimulationStatus(Constants.green,
				"Running " + date);
		if (visual) {
			TabContainer t = GUIBuilder.execute();
			t.setBackground(new Color(250, 250, 250));
			JFrame f = new JFrame();
			f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			f.add(t);
			f.setBackground(new Color(250, 250, 250));
			f.setSize(920, 440);
			f.setVisible(true);
			WriterCollection.startAll();
		}
		MainGUI.setProgressBarValue(0);
		DBConnection.CreateDataTable(date);
		String simD = Constants.id + "_" + date.replace("-", "_");
		DBConnection.removeSimData(simD);
		SimRunner.runSimulation(date);
		while (ScheduleProgram.masterFinish() != true) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		MainGUI.getInstance().setSimulationStatus(Constants.green,
				"Simulation Done");
		DBConnection.addSimData(simD);
		WriterCollection.stopAll();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
